package com.yhcui.monitor.sender;


import com.yhcui.monitor.bean.MonitorMsg;
import com.yhcui.monitor.utils.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import java.net.URLEncoder;
import java.util.List;

/**
 *
 * 钉钉限制, 每个机器人每分钟最多发送20条消息到群里，如果超过20条，会限流10分钟。
 */
@Slf4j
@Component
public class DingDingSender implements Sender {

    private static final String url = "";

    private static final String secret = "";

    @Value("${iot.link.mock:false}")
    private boolean mock;

    @Override
    public void sendMsg(MonitorMsg monitorMsg) {
        log.info("发送报警消息:{}", monitorMsg);
        String url = signUrl();
        String content = content(monitorMsg);
        if (mock) {
            log.info("url:{}, content:{}", url, content);
            return ;
        }
        String result = HttpUtil.postContent(url, content);
        log.info("url:{}, content:{}, result:{}", url, content, result);

    }


    public String content(MonitorMsg monitorMsg) {
        JSONObject root = new JSONObject();
        JSONObject atObj = new JSONObject();
        JSONArray atMobiles = new JSONArray();
        List<String> mobileList = monitorMsg.getMobiles();
        if (mobileList != null) {
            for (String mobile : mobileList) {
                atMobiles.add(mobile);
            }
        }

        atObj.put("atMobiles", atMobiles);
        atObj.put("isAtAll", monitorMsg.isAtAll());

        root.put("at", atObj);

        JSONObject textObj = new JSONObject();
        textObj.put("content", monitorMsg.getMsg());
        root.put("text", textObj);
        root.put("msgtype", "text");

        return root.toJSONString();
    }

    public String signUrl() {
        try {
            Long timestamp = System.currentTimeMillis();
            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
            return String.format(url, timestamp, sign);
        } catch (Exception e) {
            log.error("", e);
        }
        return null;
    }

    public static void main(String[] args) {
        DingDingSender dingDingSender = new DingDingSender();
        System.out.println(dingDingSender.content(null));
        String s = dingDingSender.signUrl();
        System.out.println("s:" + s);
    }
}
